<template>
  <view class="container">
    <!-- 底部抽屉 -->
    <u-popup :show="show" :round="10" @close="close" :closeable="true" :safe-area-inset-bottom="true">
      <view class="content">
        <!-- 当前余额 -->
        <view class="balance-box">
          <text class="label">当前可提现余额</text>
          <text class="amount">¥ {{ balance }}</text>
        </view>
        <!-- 提现表单 -->
        <view class="form-box">
          <u--form labelPosition="left" :model="form" labelWidth="90">
            <u-form-item label="提现金额" prop="balance" required>
              <u--input v-model="form.balance" placeholder="请输入提现金额" type="number" border="none" />
            </u-form-item>
            <u-form-item label="收款人姓名" prop="name" required>
              <u--input v-model="form.name" placeholder="请输入收款人姓名" border="none" />
            </u-form-item>
            <u-form-item :label="selectedMethod === 1 ? '银行卡号' : '收款账号'" prop="alipay" required v-if="selectedMethod !== 2">
              <u--input v-model="form.alipay" :placeholder="selectedMethod === 1 ? '请输入银行卡号' : '请输入收款账号'" border="none" />
            </u-form-item>

            <u-form-item v-if="selectedMethod === 2" label="微信收款码" prop="wxImg" required>
              <u-upload :fileList="fileList1" accept="image" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="1" :max-size="2 * 1024 * 1024" @oversize="oversize"></u-upload>
            </u-form-item>
          </u--form>
          <!-- 提现方式 -->
          <view class="method-list">
            <view v-for="(item, index) in methods" :key="index" class="method-item" :class="{ active: item.active }" @click="selectMethod(index)">
              <image class="icon" :src="item.icon" mode="aspectFit" />
              <text class="name">{{ item.name }}</text>
              <u-icon name="checkmark-circle-fill" color="#2979ff" size="20" v-if="item.active" />
            </view>
          </view>
          <u-button type="primary" text="立即提现" customStyle="margin-top: 40rpx" @click="submit" />
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { auditApi } from "@/sheep/api/index";
import { clientId, baseUrl } from "@/sheep/request/baseUrl";
export default {
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    balance: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      methods: [
        { name: "支付宝", icon: "/static/img/支付宝支付.png", active: true },
        { name: "银行卡", icon: "/static/img/银联.png", active: false },
        { name: "微信", icon: "/static/img/微信.png", active: false },
      ],
      form: {
        balance: "", //金额
        alipay: "", //账号
        type: "", //提现类型
        wxImg: "", //微信收款码
        name: "", //收款人姓名
      },
      selectedMethod: 0,
      fileList1: [],
    };
  },
  methods: {
    // 选择提现方式
    selectMethod(index) {
        this.fileList1=[]
        this.form.wxImg=''
        this.methods.forEach((item, i) => {
        item.active = i === index;
      });
      this.selectedMethod = index;
    },

    // 提交提现申请
    async submit() {
      if (!this.validateForm()) return;

      try {
          console.log("this.fileList1", this.fileList1);
          if (Array.isArray(this.fileList1)) {
          if (this.fileList1.length > 0) {
            this.fileList1.forEach((item, index) => {
              if (item.ossId == undefined || item.ossId == "undefined") {
                uni.showToast({
                  title: "图片上传有误",
                  icon: "none",
                });
                return;
              }
              if (
                item.url == undefined ||
                item.url == "undefined" ||
                item.url == null
              ) {
                return;
              }
              if (!this.form.wxImg) {
                this.form.wxImg = item.ossId;
              }
              // else {
              //   this.form.wxImg = this.form.wxImg + "," + item.ossId;
              // }
            });
          } else {
            this.form.wxImg = "";
          }
        }

        this.form.type = this.selectedMethod;
        auditApi(this.form).then((res) => {
          if (res.code === 200) {
            this.$emit("refresh");
          }
        });
        // this.show = false;
      } catch (e) {
        uni.showToast({
          title: e.message || "提交失败",
          icon: "none",
        });
      }
    },

    // 表单验证
    validateForm() {
      if (this.selectedMethod === -1) {
        uni.showToast({ title: "请选择提现方式", icon: "none" });
        return false;
      }
      if (!this.form.name) {
        uni.showToast({ title: "请输入收款人姓名", icon: "none" });
        return false;
      }
      if (!this.form.balance || Number(this.form.balance) <= 0) {
        uni.showToast({ title: "请输入正确金额", icon: "none" });
        return false;
      }

      if (!this.form.alipay && this.selectedMethod != 2) {
        uni.showToast({
          title:
            this.selectedMethod === 1 ? "请输入银行卡号" : "请输入收款账号",
          icon: "none",
        });
        return false;
      }
      if (this.selectedMethod == 2 && this.fileList1.length <= 0) {
        uni.showToast({ title: "请上传微信收款码", icon: "none" });
        return false;
      }
      return true;
    },
    close() {
      this.$emit("close");
    },
    // 上传图片
    async afterRead(event) {
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item, index) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url, lists, event);
        console.log("result", result);
        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result.url,
            name: result.fileName,
            ossId: result.ossId,
          })
        );
        fileListLen++;
      }
    },
    uploadFilePromise(url, lists, event) {
      let token = uni.getStorageSync("token");
      let headerToken = "Bearer " + token;
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: baseUrl + "/resource/oss/upload",
          filePath: url,
          name: "file",
          header: {
            Authorization: headerToken,
            clientId: clientId,
          },
          formData: {
            user: "img",
          },
          success: (res) => {
            let data = JSON.parse(res.data);
            if (data.code == 200) {
              resolve(data.data);
            } else {
              if (lists.length > 0) {
                lists.map((item, index) => {
                  this[`fileList${event.name}`].splice(index, 1);
                });
              }
              uni.showToast({
                title: data.msg,
                icon: "none",
              });
            }
          },
        });
      });
    },
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    // 文件超出大小限制
    oversize() {
      uni.showToast({
        title: "上传最大不能超过2M",
        icon: "none",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
}

.content {
  padding: 40rpx;

  .balance-box {
    text-align: center;
    padding: 30rpx 0;
    background: #f5f6fa;
    border-radius: 16rpx;
    margin-bottom: 40rpx;

    .label {
      font-size: 28rpx;
      color: #666;
      display: block;
      margin-bottom: 10rpx;
    }

    .amount {
      font-size: 48rpx;
      color: #2979ff;
      font-weight: bold;
    }
  }

  .method-list {
    margin-bottom: 40rpx;

    .method-item {
      display: flex;
      align-items: center;
      padding: 30rpx;
      background: #fff;
      border-radius: 12rpx;
      margin-bottom: 20rpx;
      border: 2rpx solid #eee;
      transition: all 0.3s;

      &.active {
        border-color: #2979ff;
        background: #f5f8ff;
      }

      .icon {
        width: 50rpx;
        height: 50rpx;
        margin-right: 20rpx;
      }

      .name {
        font-size: 32rpx;
        color: #333;
        flex: 1;
      }
    }
  }

  .form-box {
    ::v-deep .u-form-item {
      padding: 20rpx 0;

      .u-form-item__body {
        padding: 20rpx;
        background: #f5f6fa;
        border-radius: 12rpx;
      }

      .u-form-item__label {
        font-size: 28rpx;
        color: #666;
        padding-bottom: 10rpx;
      }
    }

    .u-button {
      height: 90rpx;
      border-radius: 45rpx;
      font-size: 32rpx;
    }
  }
}
</style>
